package com.hex.ds.hdtp.core.app.data.contrast.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.hex.ds.hdtp.core.app.common.enums.BasicTaskStatus;
import com.hex.ds.hdtp.core.app.common.page.PageData;
import com.hex.ds.hdtp.core.app.common.page.converter.IPageAndPageDtoConverter;
import com.hex.ds.hdtp.core.app.common.page.dto.PageDto;
import com.hex.ds.hdtp.core.app.common.util.ExcelDownUtil;
import com.hex.ds.hdtp.core.app.data.configuration.dto.requestDto.TableConvertRequestDto;
import com.hex.ds.hdtp.core.app.data.contrast.converter.ICrossDbContrastConverter;
import com.hex.ds.hdtp.core.app.data.contrast.converter.ICrossDbContrastTaskConverter;
import com.hex.ds.hdtp.core.app.data.contrast.converter.ICrossDbContrastTemplateConverter;
import com.hex.ds.hdtp.core.app.data.contrast.dto.ContrastListExcelDto;
import com.hex.ds.hdtp.core.app.data.contrast.dto.ContrastTaskExcelDto;
import com.hex.ds.hdtp.core.app.data.contrast.dto.CrossDbContrastDto;
import com.hex.ds.hdtp.core.app.data.contrast.dto.request.CrossDbContrastListRequestDto;
import com.hex.ds.hdtp.core.app.data.contrast.dto.request.CrossDbContrastRunLogRequestDto;
import com.hex.ds.hdtp.core.app.data.contrast.dto.request.CrossDbContrastTaskRequestDto;
import com.hex.ds.hdtp.core.app.data.contrast.dto.request.CrossDbContrastTemplateRequestDto;
import com.hex.ds.hdtp.core.app.data.contrast.dto.response.CrossDbContrastListResponseDto;
import com.hex.ds.hdtp.core.app.data.contrast.dto.response.CrossDbContrastTaskResponseDto;
import com.hex.ds.hdtp.core.app.data.contrast.dto.response.CrossDbContrastTemplateResponseDto;
import com.hex.ds.hdtp.core.app.data.contrast.service.*;
import com.hex.ds.hdtp.core.app.metadata.service.ISourceInfoService;
import com.hex.ds.hdtp.core.inf.common.page.Page;
import com.hex.ds.hdtp.core.inf.data.contrast.po.CrossDbContrastTaskPo;
import com.hex.ds.hdtp.core.inf.data.contrast.repository.ICrossDbContrastTaskRepository;
import com.hex.ds.hdtp.core.inf.metadata.po.SourceInfoPo;
import liquibase.util.file.FilenameUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ScheduledFuture;
import java.util.stream.Collectors;

import static com.hex.bigdata.hbda.utils.FileUtil.upload;

/**
 * @Package: com.hex.ds.hdtp.core.app.data.contrast.service.impl
 * @ClassName CrossDbContrastTaskService
 * @Description: 跨库对比任务-业务接口实现类
 * @Author: wz.li
 * @Date 2023/7/24 18:10
 * @Version v2.0.2
 **/
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class CrossDbContrastTaskService implements ICrossDbContrastTaskService {

    private final ICrossDbContrastTaskRepository crossDbContrastTaskRepository;

    private final ICrossDbContrastTaskConverter converter;

    private final ICrossDbContrastListService crossDbContrastListService;

    private final ICrossDbContrastTemplateService crossDbContrastTemplateService;

    private final ISourceInfoService sourceInfoService;

    private final IPageAndPageDtoConverter pageAndPageDtoConverter;

    private final ICrossDbContrastConverter crossDbContrastConverter;

    private final ICrossDbContrastTemplateConverter crossDbContrastTemplateConverter;

    private final ICrossDbContrastService crossDbContrastService;

    private final IContrastTaskTemplateService contrastTaskTemplateService;

    private final ICrossDbContrastRunLogService crossDbContrastRunLogService;

    private final ThreadPoolTaskScheduler threadPoolTaskScheduler;
    private Map<String, ScheduledFuture<?>> cronMap = new HashMap<>();

    @Value("${file.path}")
    private String filePath;

    @Autowired
    private ApplicationContext applicationContext;
    /*
     * @Method: queryListByPage <br>
     * @Param: [crossDbContrastTaskRequestDto, pageDto] <br>
     * @Return: com.hex.ds.hdtp.core.app.common.page.PageData <br>
     * @Description：分页查询<br>
     * @Author： wz.li<br>
     * @Date： 2023/7/24 18:10 <br>
     * @Version： V2.0.2<br>
     */
    @Override
    public PageData queryListByPage(CrossDbContrastTaskRequestDto crossDbContrastTaskRequestDto, PageDto pageDto) {
        final Page<CrossDbContrastTaskPo> pageResult = crossDbContrastTaskRepository.queryListByPage(
                converter.toCrossDbContrastTaskPo(crossDbContrastTaskRequestDto), pageAndPageDtoConverter.toPage(pageDto));
        List<CrossDbContrastTaskResponseDto> responseDtos = converter.toCrossDbContrastTaskResponseDtoList(pageResult.getData());
//        converterIdToName(responseDtos);
        return new PageData(responseDtos, pageResult.getTotal());
    }

    /**
     * @Method converterIdToName
     * @Param
     * @param responseDtos
     * @Return java.util.List<com.hex.ds.hdtp.core.app.data.contrast.dto.response.CrossDbContrastTaskResponseDto>
     * @Description 将模板与数据服务器从id转为具体的名称
     * @Author Wang zhihao
     * @Date 2023/8/2 11:29
     * @Version V1.0
     */
    private List<CrossDbContrastTaskResponseDto> converterIdToName(List<CrossDbContrastTaskResponseDto> responseDtos) {
        for (CrossDbContrastTaskResponseDto crossDbContrastTask : responseDtos) {
            List<String> templatePkId = contrastTaskTemplateService.queryTemplatePkIdByTaskPkId(crossDbContrastTask.getPkId());
            crossDbContrastTask.setContrastTemplatePkIds(templatePkId);
            // 转换模板名称
            for (String pkId : templatePkId) {
                CrossDbContrastTemplateResponseDto contrastTemplate = crossDbContrastTemplateService.queryById(pkId);
                crossDbContrastTask.setContrastTemplateName((contrastTemplate != null) ? contrastTemplate.getName() : "模板不存在");
            }
            // 转换数据服务器名称
            SourceInfoPo sourceInfoPo = null;
            try {
                sourceInfoPo = sourceInfoService.queryByPkId(crossDbContrastTask.getServerPkId());
            } catch (Exception e) {
                log.error("系统配置中数据源不存在, 对应任务名：" + crossDbContrastTask.getTaskName(), e.getMessage(), e);
            }

            crossDbContrastTask.setServerName(sourceInfoPo != null ? sourceInfoPo.getSourceName() : "数据源不存在");
        }
        return responseDtos;
    }

    /*
     * @Method: add <br>
     * @Param: [crossDbContrastTaskRequestDto] <br>
     * @Return: void <br>
     * @Description：新增<br>
     * @Author： wz.li<br>
     * @Date： 2023/7/24 18:10 <br>
     * @Version： V2.0.2<br>
     */
    @Override
    public void add(CrossDbContrastTaskRequestDto crossDbContrastTaskRequestDto) {
        String pkId = crossDbContrastTaskRepository.addWithBackPkId(converter.toCrossDbContrastTaskPo(crossDbContrastTaskRequestDto));
        int count = contrastTaskTemplateService.add(pkId, crossDbContrastTaskRequestDto.getContrastTemplatePkId());
        crossDbContrastListService.addList(pkId, crossDbContrastTaskRequestDto.getDataContrastList());
        if ( count != 1) {
            throw new RuntimeException("新增跨库对比任务失败");
        }
    }

    /**
     * @Method addWithBackId
     * @Param
     * @param crossDbContrastTaskRequestDto
     * @Return java.lang.String
     * @Description 新增并返回ID
     * @Author Wang zhihao
     * @Date 2023/8/16 17:39
     * @Version V1.0
     */
    @Override
    @Transactional
    public String addWithBackId(CrossDbContrastTaskRequestDto crossDbContrastTaskRequestDto) {
        String pkId = crossDbContrastTaskRepository.addWithBackPkId(converter.toCrossDbContrastTaskPo(crossDbContrastTaskRequestDto));
        contrastTaskTemplateService.add(pkId, crossDbContrastTaskRequestDto.getContrastTemplatePkId());
        return pkId;
    }

    /*
     * @Method: modifyById <br>
     * @Param: [crossDbContrastTaskRequestDto] <br>
     * @Return: void <br>
     * @Description：修改<br>
     * @Author： wz.li<br>
     * @Date： 2023/7/24 18:10 <br>
     * @Version： V2.0.2<br>
     */
    @Override
    public void modifyById(CrossDbContrastTaskRequestDto crossDbContrastTaskRequestDto) {
        crossDbContrastTaskRequestDto.setTotal(String.valueOf(crossDbContrastListService.queryList(new CrossDbContrastListRequestDto().setTaskPkId(crossDbContrastTaskRequestDto.getPkId())).size()));
        int count = crossDbContrastTaskRepository.modifyById(converter.toCrossDbContrastTaskPo(crossDbContrastTaskRequestDto));
        contrastTaskTemplateService.rebuildById(crossDbContrastTaskRequestDto.getPkId(), crossDbContrastTaskRequestDto.getContrastTemplatePkId());
        if(crossDbContrastTaskRequestDto.getDataContrastList() != null) {
            crossDbContrastListService.batchModify(crossDbContrastTaskRequestDto.getDataContrastList());
        }
        if (count != 1) {
            throw new RuntimeException("更新跨库对比任务失败");
        }
    }

    /*
     * @Method: removeById <br>
     * @Param: [pkId] <br>
     * @Return: void <br>
     * @Description：删除<br>
     * @Author： wz.li<br>
     * @Date： 2023/7/24 18:10 <br>
     * @Version： V2.0.2<br>
     */
    @Override
    public void removeById(String pkId) {
        int count = crossDbContrastTaskRepository.removeById(pkId);
        contrastTaskTemplateService.removeByTaskPkId(pkId);
        crossDbContrastListService.removeByTaskPkId(pkId);
        if (count != 1) {
            throw new RuntimeException("删除跨库对比任务失败");
        }
    }

    /*
     * @Method: batchRemoveById <br>
     * @Param: [pkIds] <br>
     * @Return: void <br>
     * @Description：批量删除<br>
     * @Author： wz.li<br>
     * @Date： 2023/7/24 18:10 <br>
     * @Version： V2.0.2<br>
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void batchRemoveById(List<String> pkIds) {
        for (String pkId : pkIds) {
            removeById(pkId);
        }
    }

    /**
     * @Method contrast
     * @Param dataRange
     * @Param pkIds
     * @Return void
     * @Description 批量对比
     * @Author gj.xu
     * @Date 2024/2/18 10:54
     * @Version V2.0
     */
    @Override
    public void contrast(String dataRange, List<String> pkIds) {
        for (String pkId : pkIds) {
            // 根据task任务主键查询任务对象
            CrossDbContrastTaskPo contrastTask = crossDbContrastTaskRepository.queryById(pkId);
            // 根据task任务主键查询模板主键
            List<String> templatePkIdList = contrastTaskTemplateService.queryTemplatePkIdByTaskPkId(pkId);
            // 根据任务主键查询对应的任务清单
            List<CrossDbContrastListResponseDto> contrastLists = queryContrastList(dataRange, pkId);
            toContrast(templatePkIdList, pkId, contrastTask, contrastLists);
        }
    }

    @Override
    public void doContrast(CrossDbContrastTemplateResponseDto contrastTemplate,String pkId,List<CrossDbContrastListResponseDto> contrastLists,CrossDbContrastTaskPo contrastTask) {
        // 添加跨库对比任务初始执行记录
        String runLogPkId = addContrastRunLog(pkId, contrastTemplate, contrastLists.size());
        for (CrossDbContrastListResponseDto contrastList : contrastLists) {
            contrastList.setSourceCode(sourceInfoService.queryByPkId(contrastList.getServerPkId()).getSourceCode());
            contrastList.setContrastCode(sourceInfoService.queryByPkId(contrastList.getContrastServerPkId()).getSourceCode());
            // 获取跨库对比参数
            CrossDbContrastDto crossDbContrastDto = crossDbContrastConverter.toCrossDbContrastDto(contrastTask, contrastTemplate, contrastList);
            // 开始对比
            crossDbContrastService.contrast(crossDbContrastDto, runLogPkId);
        }
    }

    @Override
    public HashMap<String,Object> importContrast(MultipartFile file) {
        HashMap<String, Object> resultMap = new HashMap<>();
        try {
            String backUpFilePath = backupUploadFile(file);
            List<ContrastTaskExcelDto> contrastTaskExcelDtos = getExcelData(backUpFilePath);
            verify(contrastTaskExcelDtos);
            saveForExcel(contrastTaskExcelDtos);
            resultMap.put("status", true);
        } catch (Exception e) {
            resultMap.put("status", false);
            resultMap.put("message", e.getMessage());
        }
        return resultMap;
    }

    private void verify(List<ContrastTaskExcelDto> contrastTaskExcelDtos) {
        // 检查任务名称为空
        for (ContrastTaskExcelDto contrastTaskExcelDto : contrastTaskExcelDtos) {
            if(contrastTaskExcelDto.getTaskName()==null){
                log.error("导入失败,任务名称不能为空");
                throw new RuntimeException("导入失败,任务名称不能为空");
            }
        }
        // 检查导入的数据源和目标数据源是否一致
        Set<String> sourceSet = contrastTaskExcelDtos.stream()
                .map(ContrastTaskExcelDto::getServerSourceCode)
                .collect(Collectors.toSet());

        Set<String> targetSet = contrastTaskExcelDtos.stream()
                .map(ContrastTaskExcelDto::getContrastSourceInfoCode)
                .collect(Collectors.toSet());

        if (sourceSet.size() != 1 || targetSet.size() != 1) {
            throw new RuntimeException("请检查导入的数据源和目标数据源是否一致");
        }

    }

    @Override
    public ByteArrayResource export(List<String> pkIds) {
        String backUpPath = createSavePath();
        String templateFilePath = "static/contrastTaskTemplate.xlsx";
        List<ContrastTaskExcelDto> contrastTaskExcelDtos = pkIds.stream()
                .map(pkId -> {
                    CrossDbContrastTaskPo crossDbContrastTaskPo = crossDbContrastTaskRepository.queryById(pkId);
                    CrossDbContrastListRequestDto crossDbContrastListRequestDto = new CrossDbContrastListRequestDto();
                    crossDbContrastListRequestDto.setTaskPkId(crossDbContrastTaskPo.getPkId());
                    List<CrossDbContrastListResponseDto> crossDbContrastListResponseDtos = crossDbContrastListService.queryList(crossDbContrastListRequestDto);
                    return crossDbContrastListResponseDtos.stream()
                            .map(crossDbContrastListResponseDto -> {
                                ContrastTaskExcelDto contrastTaskExcelDto = new ContrastTaskExcelDto();
                                BeanUtils.copyProperties(crossDbContrastListResponseDto, contrastTaskExcelDto);
                                contrastTaskExcelDto.setPkId(crossDbContrastTaskPo.getPkId());
                                String templateId = contrastTaskTemplateService.queryTemplatePkIdByTaskPkId(crossDbContrastTaskPo.getPkId()).get(0);
                                String templateName = crossDbContrastTemplateService.queryById(templateId).getName();
                                contrastTaskExcelDto.setContrastTemplate(templateName);
                                String sourceCode = sourceInfoService.queryByPkId(crossDbContrastTaskPo.getServerPkId()).getSourceCode();
                                contrastTaskExcelDto.setServerSourceCode(sourceCode);
                                String targetCode = sourceInfoService.queryByPkId(crossDbContrastTaskPo.getContrastServerPkId()).getSourceCode();
                                contrastTaskExcelDto.setContrastSourceInfoCode(targetCode);
                                contrastTaskExcelDto.setTaskName(crossDbContrastTaskPo.getTaskName());
                                return contrastTaskExcelDto;
                            })
                            .collect(Collectors.toList());
                })
                .flatMap(List::stream)
                .collect(Collectors.toList());
        String saveFilePath = backUpPath + File.separator + "比对任务.xlsx";
        ExcelDownUtil.generatedExcel(contrastTaskExcelDtos, templateFilePath, saveFilePath);

        byte[] bytes;
        try {
            bytes = Files.readAllBytes(Paths.get(saveFilePath));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return new ByteArrayResource(bytes);

    }

    private String createSavePath() {
        String savePath = filePath + File.separator + "static/downExcel/contrastTaskTemplate" + File.separator + DateUtil.today() + File.separator + DateUtil.current(false);
        FileUtil.mkdir(savePath);
        return FilenameUtils.separatorsToSystem(savePath);
    }

    private String backupUploadFile(MultipartFile multipartFile) {
        String backUpPath = FilenameUtils.separatorsToSystem(filePath + File.separator + "static/uploadFile/contrastTaskTemplate" + File.separator + DateUtil.today() + File.separator + DateUtil.current(false));
        FileUtil.mkdir(backUpPath);
        String updateFilePath = FilenameUtils.separatorsToSystem(backUpPath + File.separator);
        File file = upload(multipartFile, updateFilePath);
        log.debug("上传到服务器的EXCEL文件路径: {}", file.getPath());
        return file.getPath();
    }

    private List<ContrastTaskExcelDto> getExcelData(String backUpFilePath) {
        ExcelImportResult<ContrastTaskExcelDto> convertAfterList = readExcel(backUpFilePath);
        return convertAfterList.getList();
    }

    private ExcelImportResult<ContrastTaskExcelDto> readExcel(String backUpFilePath) {
        ImportParams importParams = new ImportParams();
        importParams.setStartRows(1);
        return ExcelImportUtil.importExcelMore(new File(backUpFilePath), ContrastTaskExcelDto.class, importParams);
    }
    @Transactional(rollbackFor = {Exception.class})
    public void saveForExcel(List<ContrastTaskExcelDto> contrastTaskExcelDtos) {
        //整合任务和比对清单
        contrastTaskExcelDtos = integrateContrastTask(contrastTaskExcelDtos);
        List<CrossDbContrastTaskPo> oldTask = crossDbContrastTaskRepository.queryList(new CrossDbContrastTaskPo());
        List<String> oldTaskName = oldTask.stream().map(CrossDbContrastTaskPo::getTaskName).collect(Collectors.toList());
        contrastTaskExcelDtos.forEach(contrastTaskExcelDto -> {
            while (oldTaskName.contains(contrastTaskExcelDto.getTaskName())) {
                contrastTaskExcelDto.setTaskName(contrastTaskExcelDto.getTaskName() + "_export");
            }
            String templatePkId = crossDbContrastTemplateService.queryByTemplateName(contrastTaskExcelDto.getContrastTemplate()).getPkId();
            CrossDbContrastTaskRequestDto crossDbContrastTaskRequestDto = new CrossDbContrastTaskRequestDto();
            BeanUtils.copyProperties(contrastTaskExcelDto, crossDbContrastTaskRequestDto);
            crossDbContrastTaskRequestDto.setContrastTemplatePkId(templatePkId);
            crossDbContrastTaskRequestDto.setStatus(BasicTaskStatus.TODO.name());
            crossDbContrastTaskRequestDto.setTotal(String.valueOf(contrastTaskExcelDto.getContrastListExcelDtos().size()));
            //自己注入自己，防止事务失效
            String taskPkId = applicationContext.getBean(CrossDbContrastTaskService.class)
                    .addWithBackId(crossDbContrastTaskRequestDto);
//            CrossDbContrastTaskService crossDbContrastTaskService = (CrossDbContrastTaskService)AopContext.currentProxy();
//            String taskPkId = crossDbContrastTaskService.addWithBackId(crossDbContrastTaskRequestDto);
            contrastTaskExcelDto.getContrastListExcelDtos().forEach(contrastListExcelDto -> {
                CrossDbContrastListRequestDto crossDbContrastListRequestDto = new CrossDbContrastListRequestDto();
                BeanUtils.copyProperties(contrastListExcelDto, crossDbContrastListRequestDto);
                crossDbContrastListRequestDto.setTaskPkId(taskPkId);
                crossDbContrastListService.add(crossDbContrastListRequestDto);
            });
        });
    }

    private List<ContrastTaskExcelDto> integrateContrastTask(List<ContrastTaskExcelDto> contrastTaskExcelDtos){
        return contrastTaskExcelDtos.stream()
                .peek(dto -> {
                    dto.setServerPkId(sourceInfoService.queryBySourceCode(dto.getServerSourceCode()).getPkId());
                    dto.setContrastServerPkId(sourceInfoService.queryBySourceCode(dto.getContrastSourceInfoCode()).getPkId());
                })
                .collect(Collectors.groupingBy(ContrastTaskExcelDto::getTaskName))
                .entrySet().stream()
                .map(entry -> {
                    ContrastTaskExcelDto firstDto = entry.getValue().get(0);
                    List<ContrastListExcelDto> listExcelDtos = entry.getValue().stream()
                            .map(dto -> {
                                ContrastListExcelDto contrastListExcelDto = new ContrastListExcelDto();
                                BeanUtils.copyProperties(dto, contrastListExcelDto);
                                return contrastListExcelDto;
                            })
                            .collect(Collectors.toList());

                    firstDto.setContrastListExcelDtos(listExcelDtos);
                    return firstDto;
                })
                .collect(Collectors.toList());
    }

    /**
     * @Method toContrast
     * @Param
     * @param templatePkIdList
     * @param pkId
     * @param contrastTask
     * @param contrastLists
     * @Return void
     * @Description 跨库对比
     * @Author Wang zhihao
     * @Date 2023/8/16 18:17
     * @Version V1.0
     */
    private void toContrast(List<String> templatePkIdList, String pkId, CrossDbContrastTaskPo contrastTask, List<CrossDbContrastListResponseDto> contrastLists) {
        //比对前记录任务状态
        LocalDateTime currentDateTime = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedDateTime = currentDateTime.format(formatter);
        crossDbContrastTaskRepository.updateStatusById(pkId,formattedDateTime);
        for (String templatePkId : templatePkIdList) {
            CrossDbContrastTemplateResponseDto contrastTemplate = crossDbContrastTemplateService.queryById(templatePkId);
            if (StrUtil.equalsAnyIgnoreCase(contrastTemplate.getIsCycleContrast(),"N")){
                ScheduledFuture<?> schedule = cronMap.get(pkId);
                if(schedule != null){
                schedule.cancel(false);
                cronMap.remove(pkId);
                }
            }
            if (StrUtil.equalsAnyIgnoreCase(contrastTemplate.getIsCycleContrast(),"Y")){
                //周期模板
                CrossDbContrastCronExec exec = new CrossDbContrastCronExec(contrastTemplate,pkId, contrastLists, contrastTask,this);
                ScheduledFuture<?> schedule = threadPoolTaskScheduler.schedule(exec, new CronTrigger(contrastTemplate.getCronExpressions()));
                cronMap.put(pkId,schedule);
            } else {
                doContrast(contrastTemplate, pkId, contrastLists, contrastTask);
            }
        }
    }

    /**
     * @Method addContrastRunLog
     * @Param
     * @Return void
     * @Description 新增任务对比记录
     * @Author Wang zhihao
     * @Date 2023/7/31 14:57
     * @Version V1.0
     */
    private String addContrastRunLog(String taskPkId, CrossDbContrastTemplateResponseDto contrastTemplate, Integer contrastTotal) {
        CrossDbContrastRunLogRequestDto crossDbContrastRunLogRequestDto  = crossDbContrastTemplateConverter.toCrossDbContrastRunLogRequestDto(contrastTemplate);
        crossDbContrastRunLogRequestDto.setTaskPkId(taskPkId);
        crossDbContrastRunLogRequestDto.setStatus("PROCESSING");
        crossDbContrastRunLogRequestDto.setContrastTotal(contrastTotal);
        crossDbContrastRunLogRequestDto.setStartTime(DateUtil.now());
        return crossDbContrastRunLogService.addWithBackPkId(crossDbContrastRunLogRequestDto);
    }

    /**
     * @Method modifyContrastRunLog
     * @Param
     * @param runLogPkId
     * @param result
     * @Return void
     * @Description 更新对比任务执行记录
     * @Author Wang zhihao
     * @Date 2023/8/1 11:03
     * @Version V1.0
     */
    private void modifyContrastRunLog(String runLogPkId, Boolean result) {
        if (result.equals(Boolean.TRUE)) {
            crossDbContrastRunLogService.modifySuccessNum(runLogPkId);
        } else {
            crossDbContrastRunLogService.modifyFailNum(runLogPkId);
        }
    }

    /**
     * @Method queryContrastList
     * @Param
     * @param dataRange
     * @param taskId
     * @Return java.util.List<com.hex.ds.hdtp.core.app.data.contrast.dto.response.CrossDbContrastListResponseDto>
     * @Description 根据任务主键查询对应的任务清单
     * @Author Wang zhihao
     * @Date 2023/8/6 21:55
     * @Version V1.0
     */
    private List<CrossDbContrastListResponseDto> queryContrastList(String dataRange, String taskId) {
        CrossDbContrastListRequestDto crossDbContrastListRequestDto = new CrossDbContrastListRequestDto().setTaskPkId(taskId);
        if ("FAIL".equals(dataRange)) {
            List<CrossDbContrastListResponseDto> crossDbContrastListResponseDtos = crossDbContrastListService.queryList(crossDbContrastListRequestDto);
            Iterator<CrossDbContrastListResponseDto> iterator = crossDbContrastListResponseDtos.iterator();
            while (iterator.hasNext()){
                CrossDbContrastListResponseDto currentValue = iterator.next();
                if("true".equals(currentValue.getStatus())){
                    iterator.remove();
                }
            }
            return crossDbContrastListResponseDtos;
        }

        return crossDbContrastListService.queryList(crossDbContrastListRequestDto);
    }
}
